import getApiData from '@/services/cpasRequest';
import { msgError } from '@/utils/msg';
import { isNumeric } from '@/utils/pub';
import { IColumnProps } from 'devextreme-react/data-grid';
import { LoadOptions, SortDescriptor } from 'devextreme/data';
import { consts } from '../consts';
import { getNotExistsColumns } from '../tableColumnData';
import { SampleField, SampleTable } from '../typing';
import { udpateRowsDataRnValue } from './samplingProjectOverallService';
import { getRealTableName, showNotDataMsg } from './service';
import { showErrorInfo } from './tools/dialogs';

/**
 * 加载样本源字段
 * @param dbname
 * @param tableName
 * @returns
 */
export async function getSampleSourceFields(
  dbname: string,
  tableName: string,
): Promise<SampleField[]> {
  const retData = await getApiData('sample.getSampleSourceFields', { dbname, tableName });

  if (!retData.ok) {
    msgError(retData.data);
    return [];
  }
  retData.data.forEach((item: any, index: number) => (item.rn = index + 1));

  return retData.data;
}
/**
 * 序号列
 * @returns
 */
export function getRnColumn(): IColumnProps {
  return {
    dataField: 'rn',
    caption: consts.xh,
    alignment: 'center',
    width: 60,
    allowEditing: false,
    allowSorting: false,
    allowFiltering: false,
  };
}
/***
 * 获取dataGrid列
 */
export function getSampleSourceColums(
  sampleSourceFields: SampleField[],
  isAddRnColumn: boolean,
  allowFiltering?: boolean,
): IColumnProps[] {
  if (sampleSourceFields.length == 0) return [];
  const columns = isAddRnColumn ? [getRnColumn()] : [];

  return columns.concat(
    sampleSourceFields.map((item) => {
      let displayWidth = item.displayWidth;
      if (typeof item.displayWidth == 'string') {
        displayWidth = Number((displayWidth + '').replace('px', ''));
      }
      if (item.enabled && allowFiltering) {
        displayWidth += 10;
      }

      return {
        dataField: item.fieldName,
        caption: item.fieldTitle,
        alignment: item.align,
        width: displayWidth,
        format: item.displayFormat,
        visible: item.enabled,
        allowFiltering: item.enabled && allowFiltering,
        allowEditing: false,
        allowSorting: true,
        dataType: item.isNum ? 'number' : 'string',
      };
    }),
  );
}

/**
 * 更新属性
 * @param curSampleTable
 * @param propName
 * @param value
 */
export function updateSampleTableProps(
  sampleTableList: SampleTable[],
  curSampleTable: SampleTable,
  propName: string,
  value: any,
) {
  sampleTableList.forEach((item: any) => {
    if (item.guid == curSampleTable.guid) {
      item[propName] = value;
    }
  });
}
export const udpateSampleTableValue = async (
  sampleTableList: SampleTable[],
  curSampleTable: SampleTable,
  dbname: string,
  fieldName: string,
  fieldValue: string,
) => {
  const retData = await getApiData('sample.udpateSampleTableValue', {
    dbname,
    tableName: curSampleTable?.tableName,
    fieldName,
    fieldValue,
  });
  if (!retData.ok) {
    msgError(retData.data);
    return;
  }
  //数据库成功后,更新本地值
  sampleTableList
    .filter((item) => item.tableName == curSampleTable?.tableName)
    .forEach((item: any) => (item[fieldName] = fieldValue));
  //更新数组字段值

  updateSampleTableArrayValue(sampleTableList);
};
//更新数据字段值
export function updateSampleTableArrayValue(sampleTableList: SampleTable[]) {
  sampleTableList.forEach((item: SampleTable, index: number) => {
    item.rn = index + 1;
    //转换为json array
    item.sampleTextFieldsArray = item.sampleTextFields ? item.sampleTextFields.split(',') : [];
    item.sampleNumFieldsArray = item.sampleNumFields ? item.sampleNumFields.split(',') : [];
    item.sortFieldsArray = item.sortFields ? item.sortFields.split(',') : [];
    try {
      item.sampleAllFieldsArray = item.fieldsInfo ? JSON.parse(item.fieldsInfo) : [];
    } catch (error) {
      msgError(item.tableTitle + '->sampleAllFieldsArray:' + error);
      item.sampleAllFieldsArray = [];
    }
  });
}

export function getSampleSourceColumsOfExists(
  sampleTable: SampleTable,
  sampleSourceFields: SampleField[],
  isAddRnColumn: boolean,
  allowFiltering?: boolean,
) {
  let columns = getSampleSourceColums(
    sampleSourceFields.filter((item) => item.visible),
    isAddRnColumn,
    allowFiltering,
  );
  const existsColumns = sampleSourceFields.length > 0;
  columns = existsColumns ? columns : getNotExistsColumns(sampleTable.tableTitle);
  return columns;
}
/**
 *
 * @param sampleTable
 * @param textFieldsSampleList  已存在的,包含抽样项目字段的 any[]
 */
export function getWhereSqlByTextFieldsSampleList(
  sampleTable: SampleTable,
  textFieldsSampleList: any[],
  isNotIn: boolean,
) {
  const sampleTextFieldsArray: string[] = sampleTable.sampleTextFieldsArray;
  const fieldNameStr = sampleTextFieldsArray
    .map((fieldName) => {
      return `isnull(cast([${fieldName}] as varchar(200)),'')`;
    })
    .join(' + ');

  const fieldValueArray = textFieldsSampleList.map((item) => {
    let fieldsStr = '';
    sampleTextFieldsArray.forEach((fieldName) => {
      fieldsStr += item[fieldName] + '';
    });
    return `'${fieldsStr}'`;
  });
  const notInStr = isNotIn ? 'not' : '';
  return (
    ' /*getWhereSqlByTextFieldsSampleList:*/ ' +
    ` and ${fieldNameStr} ${notInStr} in ( ${fieldValueArray.join(',')} )`
  );
}

/**
 * 只加载数据
 * @param sampleTable
 * @param sampleSourceFields
 * @param dataId
 * @returns
 */
export async function loadSampleSourceDataListOnly(
  dbname: string,
  sampleTable: SampleTable,
  pageIndex: number,
  pageSize: number,
  sampleSourceFields?: SampleField[],
  sortFields?: string,
  dataId?: string,
  whereSql?: string,
): Promise<any[]> {
  if (!sortFields) {
    sortFields = sampleTable.sortFieldsArray.map((item) => `[${item}]`).join(',');
  }

  const retData = await getApiData('sample.getSampleSourceDataList', {
    dbname,
    tableName: getRealTableName(sampleTable?.tableName, { data_id: dataId || '' }), //todo:要替换真值
    sortFields: sortFields,
    fields: sampleSourceFields
      ? sampleSourceFields.map((item) => `[${item.fieldName}]`).join(',')
      : '',
    pageIndex,
    pageSize,
    whereSql,
  });

  if (!retData.ok) {
    showNotDataMsg(retData.data);
    return [];
  }
  udpateRowsDataRnValue(retData.data, pageIndex, pageSize, sampleSourceFields);

  return retData.data;
}
/**
 * 获取列的排序字段
 *  remoteOperations={{  sorting: true }} //要设置为远程排序,表条可以设置属性  sorting={{ mode: 'multiple' }}
 * @param loadOptions
 * @returns
 */
export function getDataGridLoadSortFields(loadOptions: LoadOptions): string {
  let sortFields = '';
  if (loadOptions.sort) {
    sortFields = (loadOptions.sort as Array<SortDescriptor<any>>)
      .map((item: any) => `[${item.selector}] ${item.desc ? 'desc' : ''}`)
      .join(',');
  }
  return sortFields;
}

/**
 * 获取样本源表个字段不重复值
 * @param sampleTable
 * @param sampleSourceFields
 * @param dataId
 * @returns
 */
export async function getSampleSourceFieldValues(
  dbname: string,
  sampleTable: SampleTable,
  fieldName: string,
  dataId?: string,
  whereSql?: string,
): Promise<any[]> {
  const retData = await getApiData('sample.getSampleSourceFieldValues', {
    dbname,
    tableName: getRealTableName(sampleTable?.tableName, { data_id: dataId || '' }), //todo:要替换真值
    fieldName,
    whereSql,
  });

  if (!retData.ok) {
    msgError(retData.data);
    return [];
  }

  return retData.data;
}

//获取查询条件

function getFilterSql(field: string, operator: string, value: string): string {
  if (field == 'rn') return '';
  if (typeof value === 'string') {
    value = value.replace(/'/g, "''");
  }
  switch (operator) {
    case 'contains':
      return `[${field}] LIKE '%${value}%'`;
    case 'notcontains':
      return `[${field}] NOT LIKE '%${value}%'`;
    case 'startswith':
      return `[${field}] LIKE '${value}%'`;
    case 'endswith':
      return `[${field}] LIKE '%${value}'`;
    case 'isblank':
      return `[${field}] IS NULL'`;
    case 'isnotblank':
      return `[${field}] IS NOT NULL'`;
    case '=':
      return `[${field}] = '${value}'`;
    case '<>':
      return `[${field}] <> '${value}'`;
    default:
      return `[${field}] ${operator} '${value}'`;
  }
}

function getIsCondition(item: any, field: string, operator: string, value: string) {
  //如果有三元数组，则说明是单个条件
  if (item.length === 3 && typeof field == 'string' && typeof operator == 'string') {
    return true;
  }
  return false;
}
/**
 * 获取查询条件 + and
 * @param filter
 */
export function getWhereSqlByFilterAnd(filter?: any[]): string {
  let whereSql = getWhereSqlByFilter(filter);
  if (whereSql) whereSql = ' and ' + whereSql;
  return whereSql;
}
/**
 * 获取查询条件
 * @param filter
 */

export function getWhereSqlByFilter(filter?: any[]) {
  if (!filter) return '';
  let whereSql = '';
  let [field, operator, value] = filter;
  //如果有三元数组，则说明是单个条件
  if (getIsCondition(filter, field, operator, value)) {
    //只下拉一个值
    if (field == 'rn') return '';
    whereSql = getFilterSql(field, operator, value);
  } else {
    //还有其他值
    filter.forEach((item) => {
      if (typeof item === 'string') {
        whereSql += ` ${item} `;
      } else if (Array.isArray(item)) {
        let whereSqlSub = '';
        let [field, operator, value] = item;
        //如果有三元数组，则说明是单个条件
        if (getIsCondition(item, field, operator, value)) {
          whereSqlSub = getFilterSql(field, operator, value);
        } else {
          whereSqlSub = getWhereSqlByFilter(item);
        }
        whereSql += whereSqlSub;
      }
    });
    if (filter[1] == 'or') {
      whereSql = ` (1=0 or ${whereSql}) `;
    }
  }
  return whereSql;
}
/**
 * 判断字段全部是否数字
 * @param gridRef
 * @param sampleField
 * @returns
 */
export function getFieldValuesIsNumber(gridRef: any, fieldName: string) {
  const rowsData: any[] = gridRef.current.instance.getDataSource()._items;
  for (let i = 0; i < rowsData.length; i++) {
    const rowData = rowsData[i];
    if (!isNumeric(rowData[fieldName])) {
      return false;
    }
  }
  return true;
}
/**
 * 更新样本源表字段信息
 * @param sampleTable
 * @param sampleField
 * @returns
 */
export async function udpateSampleTableFieldInfo(dbname: string, sampleField: SampleField) {
  const retData = await getApiData('sample.udpateSampleTableFieldInfo', {
    dbname,
    ...sampleField,
  });

  if (!retData.ok) {
    msgError(retData.data);
    return [];
  }

  return retData.data;
}
/**
 * 获取样本源表数据最大长度
 * @param dbname
 * @param tableName
 * @param fieldName
 */
export async function getTableFieldValueMaxLen(
  dbname: string,
  tableName: string,
  fieldName: string,
  whereSql?: string,
) {
  const retData = await getApiData('sample.getTableFieldValueMaxLen', {
    dbname,
    tableName,
    fieldName,
    whereSql,
  });

  if (!retData.ok) {
    msgError(retData.data);
    return 250;
  }
  return retData.data?.length;
}
/**
 * 更新字段类型
 * @param dbname
 * @param tableName
 * @param fieldName
 * @param whereSql
 * @returns
 */
export async function alterTableFieldType(
  dbname: string,
  tableName: string,
  fieldName: string,
  sqlType: string,
) {
  const retData = await getApiData('sample.alterTableFieldType', {
    dbname,
    tableName,
    fieldName,
    sqlType,
  });

  if (!retData.ok) {
    let msg = retData.data + '';
    msg = msg.replace(
      'Error converting data type varchar to numeric.',
      '文本类型不能转换为数字类型',
    );
    msgError('修改字段类型失败: ' + msg);
    // msgError(retData.data);
  }
  return retData.ok;
}
/**
 * 获取抽样项目字段值是否唯一
 * @param curSampleTable
 */
export async function getTextFieldValueIsKey(
  dbname: string,
  tableName: string,
  sampleTextFieldsArray: string[],
) {
  const fields = sampleTextFieldsArray.map((item) => `[${item}]`).join(',');
  const retData = await getApiData('sample.getTextFieldValueIsKey', {
    dbname,
    tableName: tableName,
    fields,
  });

  if (!retData.ok) {
    let msg = retData.data + '';
    msgError('getTextFieldValueIsKey失败: ' + msg);
  }
  return retData.data.isKey;
}
/**
 * 获取抽样项目字段值是否唯一
 * @param dbname
 * @param sampleTable
 * @param sampleTextFieldsArray
 * @param dataId
 * @returns
 */
export async function getTextFieldValueIsKeyOfMsg(
  dbname: string,
  sampleTable: SampleTable,
  sampleTextFieldsArray: string[],
  dataId: string,
) {
  const tableName = getRealTableName(sampleTable.tableName, { data_id: dataId });
  const fieldTitles = sampleTable.sampleAllFieldsArray
    .filter((item) => sampleTextFieldsArray.includes(item.fieldName))
    .map((item) => item.fieldTitle)
    .join('、');
  const textFieldValueIsKey = await getTextFieldValueIsKey(
    dbname,
    tableName,
    sampleTextFieldsArray,
  );
  if (!textFieldValueIsKey) {
    showErrorInfo('', `所选字段【${fieldTitles}】有重复值,会影响抽样结果，请重新选择！`);
    return false;
  }
  return true;
}
/**
 * 获取抽样表
 * @param dbname
 * @param tableNames
 * @returns
 */
export async function getSampledTables(dbname: string, tableNames: string[]): Promise<string[]> {
  const retData = await getApiData('sample.getSampledTables', {
    dbname,
    tablesInSql: tableNames.map((item) => `'${item}'`).join(','),
  });

  if (!retData.ok) {
    msgError(retData.data);
    return [];
  }

  return retData.data.map((item: any) => item.tableName);
}
